package com.lq.javawebTest.filter;

import com.lq.javawebTest.core.*;
import com.lq.javawebTest.core.entity.HttpRequest;
import com.lq.javawebTest.core.entity.HttpResponse;
import com.lq.javawebTest.core.entity.Session;
import com.lq.javawebTest.core.inter.Filter;

import java.util.ArrayList;
import java.util.List;

public class LoginFilter implements Filter {
    @Override
    public Boolean preFilter(HttpRequest request, HttpResponse response) {
        //不进行过滤的url
        List<String> whitheNames = new ArrayList<String>();
        whitheNames.add("/login.do");
        whitheNames.add("/register.do");
        whitheNames.add("/login.html");
        whitheNames.add("/register.html");
        if(whitheNames.contains(request.getUri())){
            return true;
        }

        if(request.getHeader("Cookie")!=null){
            //从给他分配的cookie中获取id,并设置响应的session
            String cookie = request.getHeader("Cookie");
            String sessionId = cookie.split("=")[1];
            Session session = Container.getSession(sessionId);
            if(session == null || session.get("user")==null){
                HttpResponse.redirect(response,"http://localhost:8080/login.html");
                return false;
            }
            return true;
        }else{
            //如果没有cookie，就重定向页面到登陆页面
            HttpResponse.redirect(response,"http://localhost:8080/login.html");
            return false;
        }
    }

    @Override
    public Boolean postFilter(HttpRequest request, HttpResponse response) {
        return true;
    }

}
